package com.kim.net.impl;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONObject;

import android.util.Log;

import com.kim.lang.IOUtils;
import com.kim.net.NetCallback;
import com.kim.net.NetEntity;

public class NetCallbackImplBase implements NetCallback {

	private static final String TAG = "NetCallbackImplBase";

	public interface Notify {
		/**
		 * POST网络请求成功
		 * 
		 * @param netEntity
		 */
		void notifyNetCallback(NetEntity netEntity);

		/**
		 * POST网络请求失败
		 * 
		 * @param httpResponseCode
		 * @param errorMsg
		 */
		void notifyError(int httpResponseCode, String errorMsg);
	}

	final Notify notify;

	public NetCallbackImplBase(Notify notify) {
		this.notify = notify;
	}

	@Override
	public void onSuccess(int httpResponseCode, InputStream inputStream,
			NetEntity netEntity, boolean gzip) {
		try {
			String result = IOUtils.convertInputStream2String(inputStream, gzip);
			Log.e(TAG, "NetCallbackImplBase.onSuccess");
			if (netEntity != null) {
				netEntity.receiveData = result;
			}
			JSONObject jsonObject = IOUtils.string2JSON(result);
			if (netEntity != null) {
				netEntity.setResult(jsonObject);
			}
			notify.notifyNetCallback(netEntity);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onError(int httpResponseCode, String errorMsg) {
		Log.e(TAG, String.format("httpResponseCode:%s|errorMsg:%s",
				httpResponseCode, errorMsg));
		notify.notifyError(httpResponseCode, errorMsg);
	}

	@Override
	public void onOtherResponseCode(int httpResponseCode,
			InputStream inputStream, NetEntity netEntity, boolean gzip) {

	}

}
